﻿using AutoMapper;
using PagedList;
using SIG.Infrastructure.Configs;
using SIG.Infrastructure.Helper;
using SIG.InputModel.Admin.Jobs;
using SIG.Model;
using SIG.Model.Enums;
using SIG.Service;
using SIG.ViewModel;
using SIG.ViewModel.Admin.Jobs;
using SIG.WebMVC.Filters;
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using SIG.Model.Jobs;
using System.Xml.Linq;
using System.Linq;
using SIG.Resources.Admin;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class JobController : BaseController
    {
        private readonly IJobService _jobService;
        private readonly IPageMetaService _pageMetaService;
        private readonly IMapper _mapper;

        public JobController(IJobService jobService, IPageMetaService pageMetaService, IMapper mapper)
        {
            _jobService = jobService;

            _pageMetaService = pageMetaService;
            _mapper = mapper;

        }
        // GET: Admin/Job

        #region Job

        public ActionResult Index(int? page, string keyword)
        {
            JobListVM jobListVM = GetElements(page, keyword);
         
            ViewBag.PageSizes = new SelectList(Site.PageSizes());
            return View(jobListVM);

        }

        private JobListVM GetElements(int? page, string keyword)
        {
            var jobListVM = new JobListVM();

            jobListVM.Keyword = keyword;
            jobListVM.PageIndex = (page ?? 1) - 1;
            jobListVM.PageSize = SettingsManager.Job.PageSize;
            int totalCount;
            var joblist = _jobService.GetPagedElements(jobListVM.PageIndex, jobListVM.PageSize, jobListVM.Keyword, out totalCount);
            var jobVMList = _mapper.Map<List<Job>, List<JobVM>>(joblist);
            jobListVM.TotalCount = totalCount;
            jobListVM.Jobs = new StaticPagedList<JobVM>(jobVMList, jobListVM.PageIndex + 1, jobListVM.PageSize, jobListVM.TotalCount); ;
            return jobListVM;
        }


        [HttpPost]
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/JobSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }


        [HttpGet]
        public ActionResult Add()
        {
            var vJob = new JobIM();
            vJob.Active = true;
            //vJob.PageIndex = pageIndex;
            //vJob.PageSize = pageSize;
            //vJob.Keyword = keyword;


            return PartialView("_Add", vJob);
        }



        [HttpPost]
        public JsonResult Add(JobIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            var job = _mapper.Map<JobIM, Job>(vm);
            _jobService.Create(job);

            if (!string.IsNullOrEmpty(vm.Keywords) || !string.IsNullOrEmpty(vm.SEODescription))
            {
                var pageMeta = new PageMeta()
                {
                    ObjectId = job.Id,
                    Keyword = vm.Keywords.Replace('，', ','),
                    Description = vm.SEODescription,
                    ModelType = ModelType.JOB
                };
                _pageMetaService.Create(pageMeta);
            }

            int count;
            int pageSize = SettingsManager.Job.PageSize;
            var list = _jobService.GetPagedElements(0, pageSize, string.Empty,out count);
            List<JobVM> jobList = _mapper.Map<List<Job>, List<JobVM>>(list);
            AR.Data = RenderPartialViewToString("_JobList", jobList);

            AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.Job));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpGet]
        public ActionResult Edit(int id)
        {

            Job job = _jobService.GetById(id);
            if (job == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.AllowGet);
            }

            var vm = _mapper.Map<JobIM>(job);
            var pageMeta = _pageMetaService.GetPageMeta(ModelType.JOB, vm.Id);
            if (pageMeta != null)
            {
                vm.Keywords = pageMeta.Keyword;
                vm.SEODescription = pageMeta.Description;
            }

            return PartialView("_Edit", vm);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]

        public JsonResult Edit(JobIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

        
            var job = _mapper.Map<JobIM, Job>(vm);
            _jobService.Update(job);

            var pageMeta = _pageMetaService.GetPageMeta(ModelType.JOB, vm.Id);
            pageMeta = pageMeta ?? new PageMeta();

            if (!string.IsNullOrEmpty(vm.Keywords) || !string.IsNullOrEmpty(vm.SEODescription))
            {

                pageMeta.ObjectId = vm.Id;
                pageMeta.Keyword = vm.Keywords;
                pageMeta.Description = vm.SEODescription;
                pageMeta.ModelType = ModelType.JOB;

                if (pageMeta.Id > 0)
                {
                    _pageMetaService.Update(pageMeta);
                }
                else
                {
                    _pageMetaService.Create(pageMeta);
                }
            }


            var jobVM = _mapper.Map<JobVM>(job);

            AR.Id = job.Id;
            AR.Data = RenderPartialViewToString("_JobItem", jobVM);

            AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Job));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        // DELETE: /User/DeleteSite
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {

            Job vJob = _jobService.GetById(id);
                     

            _jobService.Delete(vJob);
            AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.Job));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult IsActive(int id)
        {

            var vJob = _jobService.GetById(id);
            if (vJob == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                vJob.Active = !vJob.Active;
                _jobService.Update(vJob);
                var vm = _mapper.Map<JobVM>(vJob);

                AR.Data = RenderPartialViewToString("_JobItem", vm);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Job));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }

        
        


        #endregion
    }
}